package org.ccheng.gui.login;


import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import de.felixroske.jfxsupport.FXMLController;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextArea;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.ccheng.MainApplication;
import org.ccheng.gui.index.IndexView;
import org.ccheng.xztx.util.ApiConstants;

import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.ResourceBundle;

@FXMLController
public class LoginCtrl implements Initializable, EventHandler<WindowEvent> {

    @FXML
    private TextArea httpText;

    @FXML
    public void login() {
        String content = httpText.getText();

        if (StrUtil.isBlank(content)) {
            new Alert(Alert.AlertType.NONE, "内容不能为空",
                    new ButtonType[]{ButtonType.CLOSE}).show();
            return;
        }

        // 正则校验输入内容是否合法
        if (!ReUtil.contains("http\\S+\\?\\S{0,50}sid=\\S+", content)) {
            new Alert(Alert.AlertType.NONE,
                    "内容不合法，应该为  http://xxxx/xxxx?sid=xxxx",
                    new ButtonType[]{ButtonType.CLOSE}).show();
            return;
        }

        Map<String, String> params = HttpUtil.decodeParamMap(content, StandardCharsets.UTF_8);

        String sid = params.get("sid");

        if (StrUtil.isBlank(sid)) {
            new Alert(Alert.AlertType.NONE, "链接内容无效，找不到sid",
                    new ButtonType[]{ButtonType.CLOSE}).show();
            return;
        }

        ApiConstants.setSid(sid);

        openIndex();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        MainApplication.getStage().setOnCloseRequest(this);
        if (ApiConstants.USER_SID != null) {
            openIndex();
        }
    }

    private void openIndex() {
        Platform.runLater(() -> {
            MainApplication.getStage().close();
            MainApplication.showView(IndexView.class);
        });
    }

    @Override
    public void handle(WindowEvent event) {
        System.exit(1);
    }
}
